package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.ImMsgBizSkills;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.ImMsgBizSkillsMapper;
import com.yami.shop.service.ImMsgBizSkillsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 客服自动回复表
 *
 * @author LGH
 * @date 2023-03-07 17:16:11
 */
@Service
public class ImMsgBizSkillsServiceImpl extends ServiceImpl<ImMsgBizSkillsMapper, ImMsgBizSkills> implements ImMsgBizSkillsService {

    @Autowired
    private ImMsgBizSkillsMapper imMsgBizSkillsMapper;

    @Override
    public Page<ImMsgBizSkills> page(PageParam<ImMsgBizSkills> pageParam, Long shopId, String keywords, String content) {
        return imMsgBizSkillsMapper.page(pageParam, shopId, keywords, content);
    }

    @Override
    public boolean insert(ImMsgBizSkills imMsgBizSkills){
        checkSkills(imMsgBizSkills);
        imMsgBizSkills.setStatus(1);
        imMsgBizSkills.setCreateTime(new Date());
        imMsgBizSkills.setUpdateTime(new Date());
        return save(imMsgBizSkills);
    }

    @Override
    public boolean update(ImMsgBizSkills imMsgBizSkills){
        checkSkills(imMsgBizSkills);
        imMsgBizSkills.setUpdateTime(new Date());
        return updateById(imMsgBizSkills);
    }

    @Override
    public boolean deleteById(Long id){
        ImMsgBizSkills selectOne = imMsgBizSkillsMapper.selectById(id);
        selectOne.setStatus(0);
        return updateById(selectOne);
    }

    private void checkSkills(ImMsgBizSkills imMsgBizSkills){
        ImMsgBizSkills selectOne = imMsgBizSkillsMapper.selectOne(new LambdaQueryWrapper<ImMsgBizSkills>()
                .eq(ImMsgBizSkills::getKeywords, imMsgBizSkills.getKeywords())
                .eq(ImMsgBizSkills::getShopId, imMsgBizSkills.getShopId())
                .eq(ImMsgBizSkills::getStatus, 1)
        );
        if(Objects.nonNull(selectOne)){
            if(imMsgBizSkills.getId() != null && Objects.equals(imMsgBizSkills.getId(), selectOne.getId())){
                return;
            }else{
                throw new YamiShopBindException("ymai.skills.repeat");
            }
        }
    }



}
